//
//  UIButton+Ext.swift
//  liveimoocs
//
//  Created by wenkai on 2017/12/1.
//  Copyright © 2017年 wenkai. All rights reserved.
//

import UIKit

extension UIButton {
    open func set(_ image: UIImage?, title: String?, titlePosition: UIViewContentMode, additionalSpcaing: CGFloat, state: UIControlState) {
        self.imageView?.contentMode = .center
        self.setImage(image, for: state)
        
        positionLabelRespectToImage(title: title!, position: titlePosition, spacing: additionalSpcaing)
        
        self.titleLabel?.contentMode = .center
        self.setTitle(title, for: state)
    }
    
    private func positionLabelRespectToImage(title: String, position: UIViewContentMode,
                                             spacing: CGFloat) {
        let imageSize = self.imageRect(forContentRect: self.frame)
        let titleFont = self.titleLabel?.font!
        let titleSize = title.size(withAttributes: [NSAttributedStringKey.font: titleFont!])
        
        var titleInsets: UIEdgeInsets
        var imageInsets: UIEdgeInsets
        
        switch (position){
        case .top:
            titleInsets = UIEdgeInsets(top: -(titleSize.height + spacing)/2,
                                       left: -(imageSize.width/2), bottom: (titleSize.height + spacing)/2, right: imageSize.width/2)
            imageInsets = UIEdgeInsets(top: imageSize.height/2, left: titleSize.width/2, bottom: -imageSize.height/2, right: -titleSize.width/2)
        case .bottom:
            titleInsets = UIEdgeInsets(top: (titleSize.height+spacing)/2,
                                       left: -(imageSize.width/2), bottom:-(titleSize.height+spacing)/2, right: imageSize.width/2)
            imageInsets = UIEdgeInsets(top: -(imageSize.height+spacing)/2, left: titleSize.width/2, bottom: (imageSize.height+spacing)/2, right: -titleSize.width/2)
        case .left:
            titleInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: 0, right: imageSize.width)
            imageInsets = UIEdgeInsets(top: 0, left: titleSize.width, bottom: 0,
                                       right: -(titleSize.width + spacing))
        case .right:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        default:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        self.titleEdgeInsets = titleInsets
        self.imageEdgeInsets = imageInsets
    }
}
